package com.mbigger.netty.ch7;

import com.mbigger.netty.ch2.handler.FirstServerHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.jsc.JSerialCommChannel;
import io.netty.channel.jsc.JSerialCommChannelConfig;
import io.netty.channel.jsc.JSerialCommDeviceAddress;
import io.netty.channel.oio.OioEventLoopGroup;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SerialSlave {

    public static final String PORT = "COM2";
    public static final Integer RATE = 9600;

    public static void main(String[] args) {
        EventLoopGroup workerGroup = new OioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(JSerialCommChannel.class)
                .handler(new ChannelInitializer<JSerialCommChannel>() {
                    @Override
                    protected void initChannel(JSerialCommChannel ch) throws Exception {
                        ch.config().setBaudrate(RATE).setParitybit(JSerialCommChannelConfig.Paritybit.NONE)
                                .setStopbits(JSerialCommChannelConfig.Stopbits.STOPBITS_1).setDatabits(8)
                                .setWaitTimeMillis(0).setReadTimeout(1);
                        ch.pipeline().addLast(new FirstServerHandler());
                        log.info("通道初始化！");
                    }
                });
        ChannelFuture channelFuture = bootstrap.connect(new JSerialCommDeviceAddress(PORT)).syncUninterruptibly();
        if (channelFuture != null && channelFuture.isSuccess()) {
            log.info("open seria[{}] successfully!", PORT);
        } else {
            log.error("open seria[{}] failure!", PORT);
        }
    }
}
